const cloud = require('@alipay/faas-server-sdk');

/**
 * 初始化购物车表
 */
async function createCollection(db) {
  const collectionResp = await db.getCollection('mall_shop_car');
  if (!collectionResp) {
    collectionResp = await db.createCollection('mall_shop_car');
  }
  console.log('collectionResp:', collectionResp)
  return collectionResp;
}

/**
 * 查询购物车记录
 */
async function queryCartItem(db, userId, productId) {
  const queryResp = await db.collection('mall_shop_car').where({
    userId: userId,
    productId: productId
  }).get();
  console.log('queryResp:', queryResp);
  return queryResp;
}

exports.main = async (event, context) => {
  const db = cloud.database();
  await createCollection(db);
  
  // 查询购物车记录
  const cartItems = await queryCartItem(db, event.userId, event.productId);

  // 如果购物车中存在相同的userId和productId，更新原记录的数量
  if (cartItems.length > 0) {
    const cartItem = cartItems[0];
    const newNumber = cartItem.number + event.number;

    // 更新购物车记录的数量
    const updateResp = await db.collection('mall_shop_car').where({
      _id: cartItem._id
    }).update({
      data: {
        number: newNumber,
        gmtModified: Date.now()
      }
    });

    console.log('updateResp:', updateResp);
    return updateResp;
  }

  // 如果购物车中不存在相同的userId和productId，添加新的记录
  const addResp = await db.collection('mall_shop_car').add({
    data: {
      "name": event.name,
      "price": event.price,
      "number": event.number,
      "picUrl": event.picUrl,
      "productId": event.productId,
      "userId": event.userId,
      "status": "NORMAL",
      "shopId": event.shopId,
      "gmtCreate": Date.now(),
      "shopName": event.shopName,
      "description": event.description,
      "gmtModified": Date.now()
    }
  });

  console.log('addResp:', addResp);
  return addResp;
};
